var phone = getValueByParam('phone'),
	intervalId = null,
	remainingSeconds = 60,
	duration = 300;

$(() => {
	initValue();
	initListener();
})

initValue = () => {
	$(`#current_phone`).html(phone);
}

initListener = () => {
	$("#new_phone").bind('input propertychange', (event) => {
		if (event.target.value) {
			$("#clear_phone").show(duration);
		} else {
			$("#clear_phone").hide(duration);
		}
	});
	$("#clear_phone").on('click', (e) => {
		$(`#new_phone`).val('');
		$("#clear_phone").hide(duration);
	});
	$("#code").bind('input propertychange', (event) => {
		if (event.target.value) {
			$("#clear_code").show(duration);
		} else {
			$("#clear_code").hide(duration);
		}
	});
	$("#clear_code").on('click', (e) => {
		$(`#code`).val('');
		$("#clear_code").hide(duration);
	});
	document.getElementById('get_code').addEventListener('click', debounce(handleGetCodeClick, 1000));
	// $("#get_code").on('click', (e) => {
	// 	if (handlePhone('new_phone')) {
	// 		countDown();
	// 	}
	// });
	$("#save").on('click', (e) => {
		onSave();
	});
}

handleGetCodeClick = () => {
	if (handlePhone('new_phone')) {
		countDown();
	}
}

handlePhone = (inputPhoneId) => {
	let phone = $(`#${inputPhoneId}`).val().trim();
	if (phone == '') {
		showToast('请输入新手机号');
		return false
	}
	if (phone.length != 11) {
		showToast('请输入11位新手机号');
		//$(`#new_phone`).focus();
		return false
	}
	if (!isValidPhoneNumber(phone)) {
		showToast('请输入11位有效手机号');
		//$(`#new_phone`).focus();
		return false
	}
	return true
}

countDown = () => {
	intervalId = setInterval(() => {
		if (remainingSeconds === 0) {
			remainingSeconds = 60;
			clearInterval(intervalId);
			$(`#get_code`).html('获取验证码');
			$("#get_code").removeClass('disenable');
		} else {
			$("#get_code").addClass('disenable');
			$(`#get_code`).html(remainingSeconds + "s后可重新获取");
			remainingSeconds--;
		}
	}, 1000);
}

onSave = () => {
	if (handlePhone('new_phone')) {
		let code = $(`#code`).val().trim();
		if (code == '') {
			showToast('请输入验证码');
			$(`#code`).focus();
			return
		}
		let subLoading = layer.open({
			type: 2,
			shadeClose: false,
			content: '正在提交...'
		});

		setTimeout(() => {
			layer.close(subLoading);
			showToast('修改成功！');
			goBack();
		}, 500)
	}
}
